﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Text;
using Medianamik.Core.Configuration;
using Medianamik.Core.Urls;

namespace Medianamik.Core
{
    [Serializable]
    public class MedianamikUrl : IEquatable<MedianamikUrl>
    {
        //readonly IPathBuilder _pathBuilder = new ObjectFactory<IPathBuilder>().Get();
        private IUrlDictionary urlDictionary = new ObjectFactory<IUrlDictionary>().Get();

        private static MedianamikConfigSection Config = (MedianamikConfigSection)ConfigurationManager.GetSection(ConfigurationSectionName.MEDIANAMIK);

        public MedianamikUrl(string path, Guid webSiteId, bool excludedFromIndexation, CultureInfo culture)
        {
            _path = path;
            _webSiteId = webSiteId;
            _excludedFromIndexation = excludedFromIndexation;
            _culture = culture;
        }

        public string Path { get { return '/' + _path.TrimStart('/'); } }
        private readonly string _path;

        public Guid WebSiteId
        {
            get
            {
                return _webSiteId;
            }
            set
            {
                _webSiteId = value;
                _webSite = null;
            }
        }
        private Guid _webSiteId;

        public CultureInfo Culture
        {
            get { return _culture; }
        }
        CultureInfo _culture;

        public bool ExcludedFromIndexation { get { return _excludedFromIndexation; } }
        private readonly bool _excludedFromIndexation;

        [NonSerialized]
        WebSite _webSite;
        public WebSite WebSite
        {
            get
            {
                if (_webSite == null)
                {
                    _webSite = NodeManager.GetNode<WebSite>(WebSiteId);
                    _webSite.DefaultCulture = Culture;
                }
                return _webSite;
            }
        }

        public string DisplayUrl
        {
            get
            {
                if (String.IsNullOrEmpty(_displayUrl))
                    _displayUrl = urlDictionary.GetRelativePath(WebSite.Prefix, Path);

                return _displayUrl;
            }
        }

        private string _displayUrl;

        #region IEquatable<MedianamikUrl> Members

        public bool Equals(MedianamikUrl other)
        {
            if (Object.ReferenceEquals(other, null))
            {
                return false;
            }
            if (Object.ReferenceEquals(other, this))
            {
                return true;
            }
            return (DisplayUrl == other.DisplayUrl);
        }

        public override int GetHashCode()
        {
            return DisplayUrl.GetHashCode();
        }

        #endregion
    }
}
